﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Techappy.Silverlight.Toolkit
{
    /// <summary>
    /// 容器中的元素
    /// </summary>
    internal class ChildElement
    {
        Point _position = new Point();

        public ChildElement(int index, FrameworkElement element, Size availableSize, Point center, Size itemSize, int rowsCount, double margin, double radius)
        {
            Index = index;
            Element = element;

            this.GetPosition(rowsCount, itemSize, margin);
            this.SetProjectionPanel(center, radius, availableSize);
        }

        /// <summary>
        /// 在容器中的索引
        /// </summary>
        public int Index { get; private set; }
        public FrameworkElement Element { get; private set; }

        /// <summary>
        /// 元素中心在这个容器中的位置
        /// 参考位置（不是实际布局位置）
        /// </summary>
        Point Position
        {
            get { return this._position; }
        }

        /// <summary>
        /// 是否在可视区域
        /// 在Arrange的时候根据此属性决定是否显示此元素
        /// </summary>
        public bool IsVisible { get; private set; }

        /// <summary>
        /// 计算元素的中心位置在容器中的位置
        /// </summary>
        /// <param name="rowsCount">显示元素的行数</param>
        /// <param name="itemSize">每个元素的尺寸</param>
        /// <param name="magin">元素之间的间距</param>
        private void GetPosition(int rowsCount, Size itemSize, double magin)
        {
            int col = Index / rowsCount; //第几列
            int row = Index % rowsCount;//第几行

            this._position.X= magin + itemSize.Width / 2 + col * (itemSize.Width + magin);
            this._position.Y= magin + itemSize.Height / 2 + row * (itemSize.Height + magin);
        }

        private void SetProjectionPanel(Point center, double radius, Size availableSize)
        {
            PlaneProjection projection = new PlaneProjection();
            projection.CenterOfRotationX = 0.5;
            projection.CenterOfRotationY = 0.5;
            projection.CenterOfRotationZ = -radius;

            projection.RotationY = (center.X- this._position.X) / radius * 180 / Math.PI;
            projection.RotationX = (center.Y- this._position.Y) / radius * 180 / Math.PI;

            this.Element.Projection = projection;

            this.IsVisible = Math.Abs(center.X - this._position.X) <= Math.Asin(availableSize.Width / 2 / radius) * radius;
            this.Element.Visibility = IsVisible ? Visibility.Visible : Visibility.Collapsed;
        }
    }
}
